package cn.xiaoke.damowang.lucky_audience.service.domain;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpRequest;
import cn.xiaoke.damowang.lucky_audience.entity.Arc_audits;
import cn.xiaoke.damowang.lucky_audience.entity.Archive;
import cn.xiaoke.damowang.lucky_audience.entity.Page;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
@Slf4j
public class ArchivesDomainService extends BaseSendHttpToBiliBili {

    @Override
    public List<Archive> send() {
        int current = 1;
        int pageSize = 10;
        int count = Integer.MAX_VALUE;
        int errorCount = 0;
        List<Archive> archiveList = new ArrayList<>();

        do {
            final String s = HttpRequest.get(config.getMemberPre() + String.format(config.getArchiveList(), current, pageSize))
                    .header(getHeader()).execute().body();
            final JSONObject body = JSON.parseObject(s);
            if (Objects.equals(0, body.getInteger("code"))) {
                final JSONObject data = body.getJSONObject("data");
                final Page page = data.getObject("page", Page.class);
                count = page.getCount();
                List<Arc_audits> arc_audits = data.getObject("arc_audits", new TypeReference<List<Arc_audits>>() {
                });
                arc_audits.forEach(arc -> {
                    archiveList.add(arc.getArchive());
                });
                current++;
            } else {
                if (errorCount++ > 10) {
                    log.error("重试10次失败");
                    break;
                }
                ThreadUtil.sleep(1000);
            }
        } while ((current - 1) * pageSize < count);
        log.info("视频列表: {}",JSON.toJSONString(archiveList));
        log.info("总共{}部视频",archiveList.size());
        return archiveList;
    }
}
